//
//  XJ_AddCreditCardViewController.m
//  XunJieProject
//
//  Created by xue on 2018/6/12.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_AddCreditCardViewController.h"
#import "XJ_ApplayResultViewController.h"
#import "XJ_AlextShowView.h"
#import "XJ_SelectBandView.h"
#import "XJ_BankListModel.h"
#import "TregularexpressionNSObjec.h"
#import "XJ_ApplicationDetailViewController.h"
@interface XJ_AddCreditCardViewController (){
    
    NSString * bankID;
}

@property (weak, nonatomic) IBOutlet UIButton *addCardBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *IDCardTF;
@property (weak, nonatomic) IBOutlet UITextField *CreditCardIDTF;
@property (weak, nonatomic) IBOutlet UITextField *CVN2TF;
@property (weak, nonatomic) IBOutlet UITextField *validityDateTF;
@property (weak, nonatomic) IBOutlet UITextField *bandTF;
@property (weak, nonatomic) IBOutlet UITextField *billDateTF;
@property (weak, nonatomic) IBOutlet UITextField *repayDateTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (nonatomic, strong)NSMutableArray * dataArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTop;
@property (weak, nonatomic) IBOutlet UIView *codeView;


@end

@implementation XJ_AddCreditCardViewController

- (NSMutableArray *)dataArray{
    
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return   _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getBankListData];
    _scrollViewTop.constant = SafeAreaTopHeight;
    
    if (_channalID == 3) {
        
        _codeView.hidden = YES;
        
    }else{
        _codeView.hidden = NO;
    }
    
    // Do any additional setup after loading the view from its nib.
}
-(void)creatMainUI{
    
    self.nav_titleLabel.text =@"添加信用卡";
    _getCodeBtn.backgroundColor =Color_ZhuSeDiao;
    _getCodeBtn.layer.cornerRadius =4;
    _getCodeBtn.layer.masksToBounds =YES;
    _addCardBtn.backgroundColor =Color_ZhuSeDiao;
    _addCardBtn.layer.cornerRadius =4;
    _addCardBtn.layer.masksToBounds =YES;
    
    _CreditCardIDTF.keyboardType =UIKeyboardTypeNumberPad;
    _CVN2TF.keyboardType =UIKeyboardTypeNumberPad;
    _phoneTF.keyboardType =UIKeyboardTypeNumberPad;
    _codeTF.keyboardType =UIKeyboardTypeNumberPad;
    _nameTF.enabled = NO;
    _IDCardTF.enabled = NO;
    
    _nameTF.text = _userName;
    _IDCardTF.text = _userIDNumber;
    
   
    [_CreditCardIDTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_phoneTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    
}

- (IBAction)Click_btn:(id)sender {
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    UIButton *button =(UIButton*)sender;
    switch (button.tag) {
        case 0://CVN2
        {
            XJ_AlextShowView *alext =[[XJ_AlextShowView alloc]initWithImage:@"cvn2_img"];
            [alext showXLAlertView];
            
            
        }
            break;
        case 1://有效期
        {
            XJ_AlextShowView *alext =[[XJ_AlextShowView alloc]initWithImage:@"validity_img"];
            [alext showXLAlertView];
            
            
        }
            break;
        case 2://发卡银行
        {

            XJ_SelectBandView *alext =[[XJ_SelectBandView alloc]initWithTitle:@"选择发卡银行" cellType:@"0" array:self.dataArray];
            alext.block = ^(id selectValue, id selectValueId) {
                
                XJ_BankListModel * bankModel =selectValue;
                NSMutableArray *selectArr =selectValueId;
                if (self.dataArray.count>0) {
                    [self.dataArray removeAllObjects];
                }
                [self.dataArray addObjectsFromArray:selectArr];
                self.bandTF.text  = bankModel.bankName;
                self->bankID = bankModel.bankId;
                
            };
            [alext showXLAlertView];
            
            
        }
            break;
        case 3://账单日
        {
            [BRStringPickerView showStringPickerWithTitle:nil dataSource:self.daysArr defaultSelValue:self.daysArr[4] isAutoSelect:NO resultBlock:^(id selectValue) {
                weakSelf.billDateTF.text =selectValue;
            }];
        }
            break;
        case 4://还款日
        {
            
            
            [BRStringPickerView showStringPickerWithTitle:nil dataSource:self.daysArr defaultSelValue:self.daysArr[4] isAutoSelect:NO resultBlock:^(id selectValue) {
                weakSelf.repayDateTF.text = selectValue;
                
            }];
        }
            break;
        case 5://获取验证码
        {
            if (_nameTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"姓名为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_IDCardTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"身份证为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_CreditCardIDTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"信用卡号为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_CVN2TF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"CVN2为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_validityDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"有效期为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_bandTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"发卡银行为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_billDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"账单日为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_repayDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"还款日为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_phoneTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"手机号为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (![TregularexpressionNSObjec isMobileNumber:_phoneTF.text]) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"请输入正确手机号" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            [self getCodeAction];
        }
            break;
        case 6://充值
        {
            if (_nameTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"姓名为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_IDCardTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"身份证为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_CreditCardIDTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"信用卡号为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_CVN2TF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"CVN2为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_validityDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"有效期为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_bandTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"发卡银行为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_billDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"账单日为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_repayDateTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"还款日为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (_phoneTF.text.length==0) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"手机号为空" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            if (![TregularexpressionNSObjec isMobileNumber:_phoneTF.text]) {
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"请输入正确手机号" image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
                return;
            }
            
            if (_channalID == 3) {
                
            }else
            {
                if (_codeTF.text.length==0) {
                    ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"验证码为空" image:@"pop_msg_tip_xs"];
                    [alext showXLAlertView];
                    return;
                }
            }
            
            
            [self addCardAction];
           
        }
            break;
            
        default:
            break;
    }
}

- (void)addCardAction{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
    [dic setValue:_nameTF.text forKey:@"userName"];
    [dic setValue:_IDCardTF.text forKey:@"idNumber"];
    [dic setValue:_CreditCardIDTF.text forKey:@"cardNo"];
    [dic setValue:_CVN2TF.text forKey:@"cvn2"];
    [dic setValue:_validityDateTF.text forKey:@"periodDate"];
    [dic setValue:bankID forKey:@"bankId"];
    [dic setValue:_billDateTF.text forKey:@"billDate"];
    [dic setValue:_repayDateTF.text forKey:@"backMoneyDate"];
    [dic setValue:_phoneTF.text forKey:@"mobile"];
    
    if (_channalID == 3) {
        
        [dic setValue:@"" forKey:@"verifyCode"];
        
    }else{
        
         [dic setValue:_codeTF.text forKey:@"verifyCode"];
    }
    
    
    [XJ_Utils signPost:@"card/add?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
//        XJ_ApplayResultViewController *result =[[XJ_ApplayResultViewController alloc]init];
//        result.resultType =@"1";
//        [self.navigationController pushViewController:result animated:YES];
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        NSString * url = [dataDic objectForKey:@"url"];
        
        if (url.length > 0) {
            
            XJ_ApplicationDetailViewController * VC = [[XJ_ApplicationDetailViewController alloc]init];
            VC.urlString = url;
            VC.isAddCard = YES;
            [self.navigationController pushViewController:VC animated:YES];
            
        }else{
            
             [self.navigationController popViewControllerAnimated:YES];
        }
        
       
        
    } failure:^(NSInteger recode, NSError *error) {
    }];
    
    
}
///获取验证码 修改
- (void)getCodeAction{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
//    [dic setValue:_phoneTF.text forKey:@"mobile"];
//    [dic setValue:@"4" forKey:@"verifyCodeType"];
    
    
    [dic setValue:_nameTF.text forKey:@"userName"];
    [dic setValue:_IDCardTF.text forKey:@"idNumber"];
    [dic setValue:_CreditCardIDTF.text forKey:@"cardNo"];
    [dic setValue:_CVN2TF.text forKey:@"cvn2"];
    [dic setValue:_validityDateTF.text forKey:@"periodDate"];
    [dic setValue:bankID forKey:@"bankId"];
    [dic setValue:_billDateTF.text forKey:@"billDate"];
    [dic setValue:_repayDateTF.text forKey:@"backMoneyDate"];
    [dic setValue:_phoneTF.text forKey:@"mobile"];
    
//    NSString * signString = [XJ_Utils urlWithSignValue:dic];
//    [dic setValue:[signString uppercaseString] forKey:@"sign"];
//    [XJ_Utils POSTZDX:@"card/preAdd?" parameters:dic success:^(id responseObject) {
//        [XJ_Utils alertViewWithMessage:@"验证码发送成功"];
//        [self startAnimation];
//    } failure:^(NSError *error) {
//        [XJ_Utils alertViewWithMessage:@"验证码发送失败"];
//    }];
    
    [XJ_Utils signPost:@"card/preAdd?" parameters:dic success:^(NSInteger recode, id jsonObject) {

        [XJ_Utils alertViewWithMessage:@"验证码发送成功"];
        [self startAnimation];
    } failure:^(NSInteger recode, NSError *error) {
    }];
}

- (void)getBankListData{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
    [dic setValue:@"2" forKey:@"bankType"];
    
    [XJ_Utils signPost:@"user/bankList?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        [self.dataArray removeAllObjects];
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        
        NSArray * arr = [dataDic objectForKey:@"bankList"];
        
        if (arr.count > 0) {
            
//            for (NSDictionary * dic in arr) {
//
//                XJ_BankListModel * bankListModel = [XJ_BankListModel mj_objectWithKeyValues:dic];
//
//                [self.dataArray addObject:bankListModel];
//
//            }
            
            for (int i=0; i<arr.count; i++) {
                NSDictionary *dic =arr[i];
                XJ_BankListModel * bankListModel = [XJ_BankListModel mj_objectWithKeyValues:dic];
                if (i==0) {
                    bankListModel.isSelect =YES;
                }else{
                    bankListModel.isSelect =NO;
                }
                [self.dataArray addObject:bankListModel];
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)startAnimation
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self->_getCodeBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                [self->_getCodeBtn setBackgroundColor:[UIColor orangeColor]];
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self->_getCodeBtn setTitle:[NSString stringWithFormat:@"剩余%d秒",seconds] forState:UIControlStateNormal];
                [self->_getCodeBtn setBackgroundColor:[UIColor lightGrayColor]];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
}

- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == self.phoneTF) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }else if (textField == self.CreditCardIDTF){
        
        if (textField.text.length > 19) {
            
            textField.text = [textField.text substringToIndex:19];
            
        }
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
